{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block title %}查询测试 - 在线跑批系统{% endblock %}

{% block extra_css %}
<!-- 引入CodeMirror用于SQL语法高亮 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/theme/dracula.min.css">
{% endblock %}

{% block content %}
<h1><i class="fas fa-search me-2"></i>查询测试</h1>

<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-body">
                <form method="post" novalidate>
                    {% csrf_token %}
                    
                    <div class="row">
                        <div class="col-md-12">
                            {{ form.db_connection|as_crispy_field }}
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <label class="form-label">{{ form.sql.label }}</label>
                            {{ form.sql }}
                            <small class="form-text text-muted">请输入要执行的SQL查询语句</small>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-3">
                            {{ form.page_size|as_crispy_field }}
                        </div>
                    </div>
                    
                    <div class="mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-play me-1"></i> 执行查询
                        </button>
                        <button type="button" class="btn btn-outline-secondary ms-2" id="clearSqlBtn">
                            <i class="fas fa-trash me-1"></i> 清空
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
</div>



{% if results %}
<div class="card mt-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-table me-1"></i>查询结果</h5>
        <div>
            <small class="text-muted">共 {{ total_rows }} 条记录</small>
        </div>
    </div>
    <div class="card-body">
        {% if total_rows > 0 %}
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        {% for column in columns %}
                        <th>{{ column }}</th>
                        {% endfor %}
                    </tr>
                </thead>
                <tbody>
                    {% for row in results %}
                    <tr>
                        {% for key, value in row.items %}
                        <td>
                            {% if value is None %}
                            <span class="text-muted">NULL</span>
                            {% else %}
                            {{ value|stringformat:".200s" }}  <!-- 限制显示长度 -->
                            {% endif %}
                        </td>
                        {% endfor %}
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        <!-- 分页控件 -->
        {% if total_pages > 1 %}
        <nav aria-label="分页">
            <ul class="pagination justify-content-center">
                <li class="page-item {% if current_page == 1 %}disabled{% endif %}">
                    <a class="page-link" href="?page={{ current_page|add:"-1" }}{% if request.GET.query_id %}&query_id={{ request.GET.query_id }}{% endif %}">上一页</a>
                </li>
                
                {% for p in 1|make_list %}
                {% with page_num=forloop.counter %}
                <li class="page-item {% if current_page == page_num %}active{% endif %}">
                    <a class="page-link" href="?page={{ page_num }}{% if request.GET.query_id %}&query_id={{ request.GET.query_id }}{% endif %}">{{ page_num }}</a>
                </li>
                {% endwith %}
                {% endfor %}
                
                <li class="page-item {% if current_page == total_pages %}disabled{% endif %}">
                    <a class="page-link" href="?page={{ current_page|add:"1" }}{% if request.GET.query_id %}&query_id={{ request.GET.query_id }}{% endif %}">下一页</a>
                </li>
            </ul>
        </nav>
        {% endif %}
        {% else %}
        <div class="text-center py-4">
            <div class="text-muted">
                <i class="fas fa-info-circle me-1"></i> 查询未返回任何结果
            </div>
        </div>
        {% endif %}
    </div>
</div>
{% endif %}


<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-history me-1"></i>查询历史</h5>
            </div>
            <div class="card-body">
                <div class="list-group">
                    {% for history in query_history_list %}
                    <a href="{% url 'sql_query_test' %}?query_id={{ history.id }}" class="list-group-item list-group-item-action {% if not history.is_success %}list-group-item-danger{% endif %}">
                        <div class="d-flex w-100 justify-content-between">
                            <small>{{ history.db_connection.name }}</small>
                            <small>{{ history.created_at|date:"m-d H:i" }}</small>
                        </div>
                        <p class="mb-1 text-truncate">{{ history.sql|truncatechars:500 }}</p>
                        <small>
                            {% if history.is_success %}
                            <i class="fas fa-check text-success me-1"></i> {{ history.row_count }}行, {{ history.execution_time|floatformat:2 }}秒
                            {% else %}
                            <i class="fas fa-times text-danger me-1"></i> 执行失败
                            {% endif %}
                        </small>
                    </a>
                    {% empty %}
                    <div class="text-center text-muted py-3">
                        暂无查询历史
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block extra_js %}
<!-- 引入CodeMirror及SQL模式 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/sql/sql.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/addon/hint/sql-hint.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/addon/hint/show-hint.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/addon/hint/show-hint.min.css">

<script>
    // 初始化SQL编辑器
    const sqlEditor = CodeMirror.fromTextArea(document.querySelector('textarea[name="sql"]'), {
        mode: 'text/x-sql',
        theme: 'dracula',
        lineNumbers: true,
        indentWithTabs: true,
        smartIndent: true,
        lineWrapping: true,
        matchBrackets: true,
        autoCloseBrackets: true,
        hintOptions: {
            tables: {
                // 可以在这里添加数据库表信息，用于自动提示
            }
        }
    });
    
    // 清空按钮事件
    document.getElementById('clearSqlBtn').addEventListener('click', function() {
        sqlEditor.setValue('');
    });
    
    // 数据库类型变化时，调整编辑器提示
    document.querySelector('select[name="db_connection"]').addEventListener('change', function() {
        // 这里可以根据选择的数据库类型调整SQL模式
        // 例如：MySQL、SQL Server和Oracle的SQL语法有细微差别
    });
    
    // 按Ctrl+Enter执行查询
    sqlEditor.setOption('extraKeys', {
        "Ctrl-Enter": function(instance) {
            document.querySelector('form').submit();
        },
        "Tab": function(instance) {
            instance.replaceSelection("  ", "end");
        }
    });
</script>
{% endblock %}
